import { getToken } from '@/utils/auth'
import { Notification, MessageBox } from 'element-ui'
import store from '@/store'
import _this from '@/main.js'

let websocket = null
const typeName = {
  info: '提示',
  success: '成功',
  warning: '警告',
  error: '错误'
}

export function closeWebSocket() {
  if (websocket) {
    websocket.close()
    websocket = null
  }
}

// 界面消息展示
function doOnNotificationMessage(data) {
  if (data && data.message) {
    _this.$store.dispatch('user/setUserMsgChange')

    data.title = data.title ? data.title : typeName[data.type]
    Notification({
      title: data.title,
      message: data.message,
      type: data.type,
      duration: 60 * 1000
    })
  }
}

// 用户退出登录
function doOnUserLogoutMessage(data) {
  if (websocket) {
    MessageBox.confirm('您已被强制退出系统, 您可以点击关闭以便保持本页面, 或尝试重新登录', '确认退出登录', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      showClose: false,
      closeOnPressEscape: false,
      closeOnClickModal: false
    }).then(() => {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    })
  }
}

export function initWebSocket(onMessage) {
  // debugger
  // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
  websocket = new WebSocket(process.env.VUE_APP_WS_API + '/websocket', [getToken()])
  websocket.onopen = function() {
    console.log('WebSocket连接成功')
  }

  websocket.onerror = function(e) {
    console.error('WebSocket连接发生错误')
    if (e) {
      console.error(e)
    }
  }

  websocket.onmessage = function(response) {
    if (response && response.data) {
      const data = JSON.parse(response.data)
      data.type = data.type ? data.type : 'info'
      let runOnMessage = true
      switch (data.type) {
        case 'success':
        case 'info':
        case 'warning':
        case 'error':
          doOnNotificationMessage(data)
          break
        case 'logout':
          doOnUserLogoutMessage(data)
          closeWebSocket()
          runOnMessage = false
          break
      }
      if (onMessage && runOnMessage) {
        onMessage()
      }
    }
  }
  websocket.onclose = function(e) {
    websocket = null
  }
}
